import pgzrun
import random
import time
import os

ROWS = 45
COLS = 90
CELL_SIZE = 15
IS_STOP=False

HEIGHT = (ROWS * CELL_SIZE)
WIDTH  = (COLS * CELL_SIZE)

BACK_COLOR = [0, 0, 127]

def GenCellColor():
    x=random.randint(0,3)
    if x==0:
        return [random.randint(50, 250), random.randint(50, 250), random.randint(0, 100)]
    elif x==1:
        return [random.randint(50, 250), random.randint(0, 100), random.randint(50, 250)]
    elif x==2:
        return [random.randint(0, 100), random.randint(50, 250), random.randint(50, 250)]
    else:
        return [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]

def init_map(rows, cols):
    return [[[0, BACK_COLOR] for c in range(cols)] for r in range(rows)]

world = init_map(ROWS, COLS)
next_world = init_map(ROWS, COLS)

def random_map(w):
    for r in range(ROWS):
        for c in range(COLS):
            w[r][c] = [int(random.randint(0, 7) == 0), GenCellColor()]

def draw_cell(w, r, c):
    cx = CELL_SIZE * c
    cy = CELL_SIZE * r
    cell_rect = Rect((cx, cy), (CELL_SIZE, CELL_SIZE))
    screen.draw.filled_rect(cell_rect, tuple(w[r][c][1]))

def count_neighbors(w, r, c):
    sum = 0
    clr = [0, 0, 0]
    for nr in range(r - 1, r + 1 + 1):
        for nc in range(c - 1, c + 1 + 1):
            mr=nr
            mc=nc
            
            if nr == r and nc == c:
                continue
            
            if nr < 0:
                mr = ROWS-1
            if nr >= ROWS:
                mr = 0
            
            if nc < 0:
                mc = COLS-1
            if nc >= COLS:
                mc = 0

            if w[mr][mc][0]:
                sum += 1
                clr[0] += w[mr][mc][1][0]
                clr[1] += w[mr][mc][1][1]
                clr[2] += w[mr][mc][1][2]
    if sum == 0:
        return sum, clr
    else:
        return sum, [clr[0] // sum, clr[1] // sum, clr[2] // sum]

def save():
    files=os.listdir(".")
    x=0
    name=""
    while True:
        name="LifeGameMap"+str(x)+".json"
        if name not in files:
            break
        x+=1
    os.mknod(name)
    f=open(name,'w')
    f.write('{"size":['+str(ROWS)+','+str(COLS)+','+str(CELL_SIZE)+"],\n")
    f.write('"map":[\n')
    for i in range(len(world)):
        f.write("[")
        for j in range(len(world[i])):
            f.write(str(world[i][j][0]))
            if not j==len(world[i])-1:
                f.write(",")
        f.write("]")
        if not i==len(world)-1:
            f.write(',\n')
    f.write(']}')
        
    f.close()

def next_cell(w, r, c):
    n, clr = count_neighbors(w, r, c)

    if n == 3:
        return [1, clr]
    elif n == 2:
        return w[r][c]
    else:
        return [0, BACK_COLOR]

def on_key_down(key):
    global IS_STOP,world
    if key==keys.SPACE:
        IS_STOP=not IS_STOP
    if key==keys.DELETE:
        world=init_map(ROWS,COLS)
    if key==keys.S:
        save()

def on_mouse_down(pos):
    global world
    x=pos[1]//CELL_SIZE
    y=pos[0]//CELL_SIZE
#    print(x,y)
    next_world[x][y]=[int(not world[x][y][0]),GenCellColor()]

def update():
    if not IS_STOP:
        for r in range(ROWS):
            for c in range(COLS):
                next_world[r][c] = next_cell(world, r, c)
    
    for r in range(ROWS):
        for c in range(COLS):
            world[r][c] = next_world[r][c]
            
    time.sleep(0.3)

def draw():
    screen.fill(tuple(BACK_COLOR))
    for r in range(ROWS):
        for c in range(COLS):
            if world[r][c][0]:
                draw_cell(world, r, c)

random_map(world)

pgzrun.go()